<template>
  <div v-if="loading" class="loading-container">
    加载课程详情中...
  </div>
  
  <div v-else-if="course" class="container mx-auto px-4 py-8">
    <div class="bg-white rounded-xl shadow-lg p-6 mb-8">
      <h1 class="text-3xl font-bold text-gray-800 mb-4">{{ course.title }}</h1>
      
      <div class="flex flex-wrap gap-4 text-sm text-gray-600 mb-6">
        <div class="flex items-center">
          <svg class="w-5 h-5 mr-2 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4"/>
          </svg>
          上课老师: {{ course.teachername || '未知' }}
        </div>
        <div class="flex items-center">
          <svg class="w-5 h-5 mr-2 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/>
          </svg>
          开始时间: {{ formatDate(course.startTime) }}
        </div>
        <div class="flex items-center" v-if="course.category">
          <svg class="w-5 h-5 mr-2 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 3v4M3 5h4M6 17v4m-2-2h4m5-16l2.286 6.857L21 12l-5.714 2.143L13 21l-2.286-6.857L5 12l5.714-2.143L13 3z"/>
          </svg>
          分类: {{ course.category }}
        </div>
      </div>
      
      <div class="mb-8">
        <h2 class="text-xl font-semibold text-gray-800 mb-3">课程简介</h2>
        <p class="text-gray-700 leading-relaxed whitespace-pre-wrap">{{ course.body || course.description }}</p>
      </div>
    </div>
    
    <!-- 标签页内容 -->
    <div class="bg-white rounded-xl shadow-lg p-6">
      <div class="tabs flex mb-6 border-b border-gray-200">
        <div 
          class="tab-item cursor-pointer px-6 py-3"
          :class="{ active: activeTab === 'tasks' }"
          @click="activeTab = 'tasks'"
        >
          课程任务
        </div>
        <div 
          class="tab-item cursor-pointer px-6 py-3"
          :class="{ active: activeTab === 'comments' }"
          @click="activeTab = 'comments'"
        >
          课程评价 ({{ userComments.length }})
        </div>
      </div>
      
      <!-- 课程任务内容 -->
      <div v-if="activeTab === 'tasks'">
        <!-- 任务统计信息 -->
        <div class="mb-6 p-4 bg-blue-50 rounded-lg">
          <div class="flex justify-between items-center">
            <div>
              <h3 class="text-lg font-medium text-blue-800">任务完成情况</h3>
              <p class="text-sm text-blue-600 mt-1">共 {{ tasks.length }} 个任务，已完成 {{ completedTasks }} 个</p>
            </div>
            <div class="w-32 h-32">
              <div class="w-full h-full rounded-full border-8 border-blue-200 relative flex items-center justify-center">
                <div class="w-full h-full rounded-full border-8 border-blue-500 absolute" :style="taskCompletionStyle"></div>
                <span class="text-2xl font-bold text-blue-700">{{ completionPercentage }}%</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 任务列表 -->
        <div v-if="processedTasks.length > 0" class="space-y-4" :key="forceUpdateKey">
          <div 
            v-for="task in processedTasks" 
            :key="task.id"
            class="task-card bg-white border rounded-lg overflow-hidden transition-all duration-300 hover:shadow-md"
          >
            <div class="p-5">
              <div class="flex justify-between items-start mb-3">
                <h3 class="text-lg font-medium text-gray-800 flex items-center gap-2">
                  <span class="w-5 h-5 rounded-full border border-gray-300 flex-shrink-0 cursor-pointer" 
                        @click="toggleTaskStatus(task)"
                        :class="{ 'bg-green-500 border-green-500': task.status === '已完成' }">
                    <svg v-if="task.status === '已完成'" class="w-4 h-4 text-white" fill="currentColor" viewBox="0 0 20 20">
                      <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"/>
                    </svg>
                  </span>
                  {{ task.title }}
                </h3>
                <span class="text-sm font-medium px-2.5 py-0.5 rounded-full"
                      :class="{
                        'bg-green-100 text-green-800': task.status === '已完成',
                        'bg-yellow-100 text-yellow-800': isTaskOverdue(task) && task.status !== '已完成',
                        'bg-blue-100 text-blue-800': !isTaskOverdue(task) && task.status !== '已完成'
                      }"
                >
                  {{ task.status || '未完成' }}
                </span>
              </div>
              
              <div class="mb-4">
                <p class="text-gray-600">{{ task.description || task.content }}</p>
              </div>
              
              <div class="flex flex-wrap gap-4 text-sm">
                <div class="flex items-center text-gray-500">
                  <svg class="w-4 h-4 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/>
                  </svg>
                  开始时间: {{ formatDate(task.startTime || task.start_time) }}
                </div>
                <div class="flex items-center"
                     :class="{ 'text-red-500': isTaskOverdue(task), 'text-gray-500': !isTaskOverdue(task) }">
                  <svg class="w-4 h-4 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
                  </svg>
                  截止时间: {{ formatDate(task.deadline) }}
                </div>
                <div v-if="task.endTime" class="flex items-center text-gray-500">
                  <svg class="w-4 h-4 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z"/>
                  </svg>
                  结束时间: {{ formatDate(task.endTime || task.end_time) }}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-else class="text-center py-16 text-gray-500">
          <svg class="w-16 h-16 mx-auto mb-4 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"/>
          </svg>
          <h3 class="text-lg font-medium">暂无课程任务</h3>
          <p class="mt-2">该课程还没有添加任何任务项</p>
        </div>
      </div>
      
      <!-- 课程评价内容 -->
      <div v-if="activeTab === 'comments'">
        <!-- 评价输入框 -->
        <div v-if="auth.isLoggedIn" class="mb-8 bg-gray-50 p-6 rounded-lg">
          <div class="flex items-start gap-4">
            <div class="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center text-blue-600 shrink-0">
              <span class="font-medium">{{ auth.user?.username?.charAt(0) || '?' }}</span>
            </div>
            <div class="flex-grow">

              <textarea 
                v-model="newComment"
                rows="3"
                placeholder="写下您对这门课程的评价..."
                class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/30 transition-all"
              ></textarea>
              <div class="flex justify-end mt-3">
                <button 
                  @click="submitComment"
                  class="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors"
                  :disabled="!newComment.trim()"
                >
                  发表评价
                </button>
              </div>
            </div>
          </div>
        </div>
        <div v-else class="text-sm text-gray-600 mb-6">
          登录后才能发表评价，<router-link to="/login" class="text-blue-600 hover:underline">去登录</router-link>
        </div>
        
        <!-- 评价列表 -->
        <div v-if="userComments.length > 0" class="space-y-6">
          <div 
            v-for="comment in userComments" 
            :key="comment.id"
            class="p-4 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors"
          >
            <div class="flex justify-between items-start mb-2">
              <div class="flex items-center">
                <div class="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center text-blue-600 mr-3">
                  <span class="font-medium">{{ comment.userName?.charAt(0) || '?' }}</span>
                </div>
                <div>
                  <p class="font-medium text-gray-800">{{ auth.userName || '匿名用户' }}</p>
                  <p class="text-xs text-gray-500">ID: {{ comment.userid }} | {{ formatDate(comment.addedTime) }}</p>
                </div>
              </div>
            </div>
            <p class="text-gray-700 pl-13">{{ comment.body }}</p>
          </div>
        </div>
        <div v-else class="text-center py-10 text-gray-500">
          暂无您的评价，来发表第一条评价吧！
        </div>
      </div>
    </div>
  </div>
  
  <div v-else class="container mx-auto px-4 py-8 text-center text-gray-500">
    加载课程详情中...
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useAuthStore } from '../store/auth'
import api from '../services/api'

const route = useRoute()
const auth = useAuthStore()

const course = ref(null)
// 添加一些初始化的mock任务数据，但不设置具体时间
const tasks = ref([
  { id: 1001, title: 'JavaScript 基础练习', courseId: 1, content: '完成10道JavaScript基础习题', status: '未完成' },
  { id: 1002, title: '函数和作用域', courseId: 1, content: '理解JavaScript函数和作用域概念', status: '已完成' }
])

// 计算属性：返回带有正确时间的任务列表
const processedTasks = computed(() => {
  // 简化实现，确保能够正确地反映任务状态的变化
  if (!course.value || !course.value.startTime || !tasks.value.length) {
    return tasks.value
  }
  
  // 获取课程发布时间
  const courseStartTime = new Date(course.value.startTime)
  
  // 为每个任务设置正确的时间
  return tasks.value.map(task => {
    // 直接返回原始任务对象，确保状态变化能够正确反映
    return {
      ...task,
      // 设置任务开始时间为课程发布时间（同时支持两种字段格式）
      startTime: courseStartTime.toISOString().split('T')[0],
      start_time: courseStartTime.toISOString().split('T')[0],
      // 计算任务结束时间：课程开始后一个月（同时支持两种字段格式）
      endTime: new Date(courseStartTime.getTime() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      end_time: new Date(courseStartTime.getTime() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      // 设置截止时间为结束时间的23:59:59
      deadline: new Date(courseStartTime.getTime() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0] + 'T23:59:59'
    }
  })
})

// 监控课程数据变化
watch(course, (newCourse, oldCourse) => {
  console.log('课程数据变化 - 新:', newCourse, '旧:', oldCourse)
  if (newCourse && newCourse.startTime) {
    console.log('课程发布时间已更新:', newCourse.startTime)
  }
}, { deep: true })

// 监控处理后的任务列表变化
watch(processedTasks, (newTasks) => {
  console.log('处理后的任务列表已更新:', newTasks)
}, { deep: true })
const comments = ref([])
const activeTab = ref('tasks')
const newComment = ref('')
const loading = ref(true) // 添加加载状态

// 计算属性，只返回登录用户的评论
const userComments = computed(() => {
  if (auth.isLoggedIn && auth.userId) {
    // 先过滤出用户的评论，然后反转顺序，确保是倒序显示
    return comments.value.filter(comment => comment.userid === parseInt(auth.userId)).reverse()
  } else {
    return []
  }
})

// 计算已完成的任务数量
const completedTasks = computed(() => {
  return tasks.value.filter(task => task.status === '已完成').length
})

// 计算完成百分比
const completionPercentage = computed(() => {
  if (tasks.value.length === 0) return 0
  return Math.round((completedTasks.value / tasks.value.length) * 100)
})

// 生成任务完成进度的CSS样式
const taskCompletionStyle = computed(() => {
  const percentage = completionPercentage.value
  // 计算SVG圆形路径样式
  const radius = 44 // 圆的半径
  const circumference = 2 * Math.PI * radius
  const offset = circumference - (percentage / 100) * circumference
  return {
    transform: 'rotate(-90deg)',
    transformOrigin: 'center',
    borderTopColor: '#3b82f6',
    borderRightColor: '#3b82f6',
    borderBottomColor: '#3b82f6',
    borderLeftColor: percentage < 50 ? '#e5e7eb' : '#3b82f6'
  }
})

// 监听评论数据和用户登录状态变化，自动过滤评论
const filterComments = () => {
  if (auth.isLoggedIn && auth.userId) {
    userComments.value = comments.value.filter(comment => comment.userid === parseInt(auth.userId))
  } else {
    userComments.value = []
  }
}

// 监听评论数据变化
watch(() => comments.value, () => {
  filterComments()
}, { deep: true })

// 监听用户登录状态变化
watch(() => [auth.isLoggedIn, auth.userId], () => {
  filterComments()
})

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
}

// 检查任务是否已过期
const isTaskOverdue = (task) => {
  if (!task.deadline) return false
  const now = new Date()
  const deadline = new Date(task.deadline)
  return now > deadline && task.status !== '已完成'
}

// 临时状态标志，用于触发UI更新
const forceUpdateKey = ref(0);

// 切换任务完成状态
const toggleTaskStatus = (task) => {
  try {
    // 1. 获取新状态
    const newStatus = task.status === '已完成' ? '未完成' : '已完成';
    
    // 2. 直接更新UI使用的任务对象状态（这是最重要的，因为UI直接使用这个对象）
    task.status = newStatus;
    
    // 3. 同时也更新原始tasks数组中的任务状态，确保数据一致性
    const taskIndex = tasks.value.findIndex(t => t.id === task.id);
    if (taskIndex !== -1) {
      // 创建一个新的任务对象，确保Vue能够检测到变化
      const updatedTask = { ...tasks.value[taskIndex] };
      updatedTask.status = newStatus;
      
      // 替换原始数组中的任务对象
      tasks.value[taskIndex] = updatedTask;
      
      // 强制重新赋值整个数组，确保Vue能够检测到变化
      tasks.value = [...tasks.value];
    }
    
    // 4. 尝试调用API更新任务状态
    api.updateTaskStatus(task.id, newStatus).catch(error => {
      console.log('任务状态已在前端更新，但服务器更新失败:', error);
    });
  } catch (error) {
    console.error('更新任务状态时出错:', error);
  }
}

// 监控原始tasks数组的变化，确保processedTasks能正确更新
watch(tasks, (newTasks) => {
  console.log('原始tasks数组发生变化，新值:', newTasks);
  // processedTasks计算属性会自动重新计算
}, { deep: true })

// 加载课程详情
const loadCourseDetail = async () => {
  try {
    console.log('发送API请求获取课程详情:', route.params.id)
    const res = await api.getCourse(route.params.id)
    console.log('课程详情API响应:', res)
    if (res.data ) {
      course.value = res.data
    }
  } catch (error) {
    console.error('加载课程详情失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载课程任务
const loadCourseTasks = async () => {
  try {
    console.log('发送API请求获取课程任务:', route.params.id)
    // 将route.params.id转换为整数类型
    const res = await api.getTasksByCourseId(parseInt(route.params.id))
    console.log('课程任务API响应:', res)
    if (res && res.data && res.data.errno === 0 && res.data.data) {
      tasks.value = res.data.data
    }
  } catch (error) {
    console.error('加载课程任务失败:', error)
  }
}

// 加载课程评价
const loadCourseComments = async () => {
  try {
    console.log('发送API请求获取课程评价:', route.params.id)
    // 传入typeIndex、userid、articleid参数
    const res = await api.getCommentsByCourseId(route.params.id)
    console.log('课程评价API响应:', res)
    if (res.data) {
      comments.value = res.data
      // 移除：userComments现在是计算属性，不需要手动过滤
    }
  } catch (error) {
    console.error('加载课程评价失败:', error)
  }
}

// 发表评价
const submitComment = async () => {
  if (!newComment.value.trim()) {
    alert('评价内容不能为空')
    return
  }
  
  try {
    // 确保用户已登录且有用户ID
    if (!auth.isLoggedIn || !auth.userId) {
      alert('请先登录再发表评价')
      return
    }
    
    const commentData = {
      // 传入body、userid和articleid参数
      body: newComment.value.trim(),        // 评价内容（输入框）
      userid: auth.userId,                  // 用户ID
      articleid: route.params.id,           // 课程ID（文章ID）
      replyType: '课程'
    }
    
    console.log('发送API请求提交评价:', commentData)
    const res = await api.addComment(commentData)
    console.log('提交评价API响应:', res)
    if ( res.data ) {
      // 清空输入框
      newComment.value = ''
      // 重新加载评价列表
      loadCourseComments()
      // 显示成功提示
      alert('评价发表成功！')
    } else {
      alert('评价发表失败，请稍后重试')
    }
  } catch (error) {
    console.error('提交评价失败:', error)
    alert('网络错误，请检查网络连接后重试')
  }
}

// 页面加载时获取数据
onMounted(async () => {
  // 先加载课程详情
  await loadCourseDetail()
  // 然后加载任务（此时课程数据已加载完成）
  await loadCourseTasks()
  // 最后加载评论
  loadCourseComments()
})
</script>

<style scoped>
.tab-item {
  padding: 10px 20px;
  margin-right: 10px;
  border-bottom: 2px solid transparent;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  color: #666;
}

.tab-item.active {
  color: #3b82f6;
  border-bottom-color: #3b82f6;
  font-weight: 600;
}

.tab-item:hover {
  color: #3b82f6;
}

/* 任务卡片样式 */
.task-card {
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
}

.task-card:hover {
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  border-color: #cbd5e1;
  transform: translateY(-1px);
}

/* 加载动画样式 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  font-size: 18px;
  color: #666;
}

/* 评价相关样式增强 */
textarea {
  resize: vertical;
  min-height: 100px;
}

button:disabled {
  background-color: #93c5fd;
  cursor: not-allowed;
}

/* 评价卡片动画效果 */
.space-y-6 > div {
  transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
}

.space-y-6 > div:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}
</style>